class WSSHClient {
  constructor(options) {
    this.options = options
    this.term = new Terminal({
      // cols: 97,
      rows: 37,
      cursorBlink: true, // 光标闪烁
      cursorStyle: "bar", // 光标样式 null | 'block' | 'underline' | 'bar'
      scrollback: 800, // 回滚
      tabStopWidth: 8, // 制表宽度
      screenKeys: true
    });
    this.term.on("data", data => this.sendClientData(data))
    this.term.open(document.getElementById('terminal'))

    // 在页面上显示连接中...
    this.term.write(this.getGreenStr('正在连接服务器...'));

    this.createWs()
  }

  createWs() {
    let endpoint = _generateEndpoint();

    if (window.WebSocket) {
      //如果支持websocket
      this._connection = new WebSocket(endpoint);
    } else {
      //否则报错
      this.writeError("不支持WebSocket");
    }

    this._connection.onopen = () => this._connection.send(JSON.stringify(this.options))

    this._connection.onmessage = evt => this.write(evt.data.toString())

    this._connection.onclose = evt => {
      this.write("\r\nError 连接已断开")
      setTimeout(() => {
        this.createWs()
      })
    }
  }

  clear() {
    this.term.clear()
  }

  send(data) {
    this._connection.send(JSON.stringify(data))
  }

  sendClientData(data) {
    //发送指令
    switch (this._connection.readyState) {
      case WebSocket.CONNECTING:
        console.error("正在连接中")
        break
      case WebSocket.OPEN:
        this._connection.send(JSON.stringify({"operate": "command", "command": data}))
        break
      case WebSocket.CLOSING:
        console.error("正在关闭中")
        break
      case WebSocket.CLOSED:
        console.error("已关闭")
        break
      default:
        break
    }
  }

  write(str) {
    this.term.write(str)
  }

  writeError(err) {
    this.term.write(this.getRedStr(err) + '\r\n');
  }

  getGreenStr(str) {
    return '\x1B[32m' + str + '\x1B[0m'
  }

  getRedStr(str) {
    return '\x1B[1;3;31mError: ' + str + '\x1B[0m'
  }
}

function _generateEndpoint() {
  let protocol
  if (window.location.protocol === 'https:') {
    protocol = 'wss://';
  } else {
    protocol = 'ws://';
  }
  return protocol + '127.0.0.1:8080/webssh';
}
